/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package multiface.web.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import multiface.valentinorusso.jpa.util.PersistenceManager;
import multiface.valentinorusso.jpa.Utente;

/**
 *
 * @author Diego64
 */
public class Util {

    public static final int RECORD_PAG = 25;
    public static final int MAX_IMAGE_VIEWALL = 250;
    public static final int MAX_VIDEO_VIEWALL = 50;
    
    public static void logDB(HttpServletRequest request){
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        HttpSession s = request.getSession();
        Utente uuu = (Utente) s.getAttribute("admin");
        multiface.valentinorusso.jpa.Log lo = new multiface.valentinorusso.jpa.Log();
        lo.setDataora(new java.util.Date());
        lo.setAction(request.getParameter("action"));
        lo.setLog(Util.mapToString(request.getParameterMap()));
        lo.setNominativo(uuu.getNome() + " " + uuu.getCognome());
        em.getTransaction().begin();
        em.persist(lo);
        em.getTransaction().commit();
        em.close();
    }
    public static void logDB(HttpServletRequest request, Exception ex){
        EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        HttpSession s = request.getSession();
        Utente uuu = (Utente) s.getAttribute("admin");
        multiface.valentinorusso.jpa.Log lo = new multiface.valentinorusso.jpa.Log();
        lo.setDataora(new java.util.Date());
        lo.setAction("ERROR:"+request.getParameter("action"));
        lo.setLog(Util.StampaStackError(ex));
        lo.setNominativo(uuu.getNome() + " " + uuu.getCognome());
        em.getTransaction().begin();
        em.persist(lo);
        em.getTransaction().commit();
        em.close();
    }

    public static String mapToString(Map<String, String[]> map) {
        String s = "";
        int c = 0;
        for (Object key : map.keySet()) {
            String keyStr = (String) key;
            if (!keyStr.contains("descrizione") && !keyStr.contains("psw") && !keyStr.contains("password")) {
                if (c > 0) {
                    s += ",";
                }
                String[] value = map.get(keyStr);
                s += (key + ":" + value[0]);
                c++;
            }
        }

        return s.toString();
    }

    public static String FormatData(Date d) {
        return FormatData(d, "dd/MM/yyyy hh:mm");

    }

    public static String FormatData(Date d, String formatter) {
        SimpleDateFormat f = new SimpleDateFormat(formatter);
        return f.format(d);
    }

    public static String getPathForErrorLogin() {
        return "/";
    }

    public static void RinominaFile(File f, File out) {

        if (f.renameTo(out)) {
            //System.out.println("---------\nFile " + f.getAbsolutePath() + "\nRinominato in\n" + out.getAbsolutePath());
        } else {
            //System.out.println("-------\nNon è stato possibile rinominare il file\n-----------------");
        }

    }

    public static void copyFile(File in, File out) {
        try {
            FileInputStream fis = new FileInputStream(in);
            FileOutputStream fos = new FileOutputStream(out);

            byte[] buf = new byte[1024];
            int i = 0;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
        } catch (Exception e) {
            //System.out.println(StampaStackError(e));
        }

    }

    public static String convertByte(long b) {
        String um = "Byte";
        String val = "";

        if (b > 1024 && b < (1024 * 1024)) {
            um = "KByte";
            double d = (double) b / 1024;
            val = (Math.round(d * 100.00) / 100.00) + "";
        }

        if (b > (1024 * 1024) && b < (1024 * 1024 * 1024)) {
            um = "MByte";
            double d = (double) b / (1024 * 1024);
            val = (Math.round(d * 100.00) / 100.00) + "";
        }

        if (b > (1024 * 1024 * 1024)) {
            um = "GByte";
            double d = (double) b / (1024.00 * 1024.00 * 1024.00);
            val = (Math.round(d * 100.00) / 100.00) + "";
        }

        return val + " " + um;
    }

    private static String getMese(int m) {
        String mese = "";
        if (m == 0) {
            mese = "gen";
        }

        if (m == 1) {
            mese = "feb";
        }

        if (m == 2) {
            mese = "mar";
        }

        if (m == 3) {
            mese = "apr";
        }

        if (m == 4) {
            mese = "mag";
        }

        if (m == 5) {
            mese = "giu";
        }

        if (m == 6) {
            mese = "lug";
        }

        if (m == 7) {
            mese = "ago";
        }

        if (m == 8) {
            mese = "set";
        }

        if (m == 9) {
            mese = "ott";
        }

        if (m == 10) {
            mese = "nov";
        }

        if (m == 11) {
            mese = "dic";
        }

        return mese;

    }

    public static String toStringTimestampITA(
            Timestamp ts) {
        if (ts != null) {

            String mese = getMese(ts.getMonth());


            String day = ts.getDate() + "";


            String s = day + " " + mese + " " + (ts.getYear() + 1900);
            return s;
        } else {
            return "(Nessuna Data)";
        }

    }

    public static String toStringTimestampITAORE(
            Timestamp ts) {
        if (ts != null) {

            String mese = getMese(ts.getMonth());


            String day = ts.getDate() + "";

            String ora;

            if (ts.getHours() < 10) {
                ora = "0" + (ts.getHours());
            } else {
                ora = (ts.getHours()) + "";
            }

            String min;
            if (ts.getMinutes() < 10) {
                min = "0" + (ts.getMinutes());
            } else {
                min = (ts.getMinutes()) + "";
            }

            String s = day + " " + mese + " " + (ts.getYear() + 1900) + " - " + ora + ":" + min;
            return s;
        } else {
            return "(Nessuna Data)";
        }

    }

    public static String toStringTimestampAMG(Timestamp ts) {
        if (ts != null) {
            String mese;
            if (ts.getMonth() < 9) {
                mese = "0" + (ts.getMonth() + 1);
            } else {
                mese = (ts.getMonth() + 1) + "";
            }

            String day;
            if (ts.getDate() < 10) {
                day = "0" + (ts.getDate());
            } else {
                day = (ts.getDate()) + "";
            }

            String s = (ts.getYear() + 1900) + "-" + mese + "-" + day;
            return s;
        } else {
            return "(Nessuna Data)";
        }

    }

    public static String toStringTimestampAMGO(
            Timestamp ts) {
        if (ts != null) {
            String mese;
            if (ts.getMonth() < 9) {
                mese = "0" + (ts.getMonth() + 1);
            } else {
                mese = (ts.getMonth() + 1) + "";
            }

            String day;
            if (ts.getDate() < 10) {
                day = "0" + (ts.getDate());
            } else {
                day = (ts.getDate()) + "";
            }

            String s = (ts.getYear() + 1900) + "-" + mese + "-" + day + " ore: " + ts.getHours();
            return s;
        } else {
            return "(Nessuna Data)";
        }

    }

    public static String toStringTimestampAMGOM(
            Timestamp ts) {
        if (ts != null) {
            String mese;
            if (ts.getMonth() < 9) {
                mese = "0" + (ts.getMonth() + 1);
            } else {
                mese = (ts.getMonth() + 1) + "";
            }

            String day;
            if (ts.getDate() < 10) {
                day = "0" + (ts.getDate());
            } else {
                day = (ts.getDate()) + "";
            }

            String s = (ts.getYear() + 1900) + "-" + mese + "-" + day + " " + ts.getHours() + ":" + ts.getMinutes();
            return s;
        } else {
            return "(Nessuna Data)";
        }

    }

    public static LinkedList sortList(
            LinkedList l) {
        Object[] a = l.toArray();
        Arrays.sort(a);

        LinkedList s = new LinkedList();
        for (int i = 0; i
                < a.length; i++) {
            s.add(a[i].toString());
        }

        return s;
    }

    public static void eliminaFile(String Dirf, boolean delContCartella) {
        File f = new File(Dirf);

        //System.out.println("------------------------ELIMINAZIONE FILE---------------------");
        //System.out.println("File :" + Dirf);

        if (f.exists()) {
            //System.out.println("il file/dir esiste");
        } else {
            //System.out.println("il file/dir non esiste");
        }

        if (f.canWrite()) {
            //System.out.println("il file/dir e scivibile");
        } else {
            //System.out.println("il file/dir non è scrivibile");
        }

        if (f.isDirectory()) {
            if (delContCartella) {
                //System.out.println("E' una cartella quindi prima vanno cancellati tutti i file "
                // + "al suo interno perche è stato inpstato cosi");

                File[] files = f.listFiles();

                for (int i = 0; i < files.length; i++) {
                    eliminaFile(files[i].getAbsolutePath(), true);
                }
            }
            if (f.delete()) {
                //System.out.println("Ho cancellato la directory");
            } else {
                //System.out.println("Impossibile cancellare la directory.Presenti file al proprio interno");
            }

        } else {
            if (f.delete()) {
                //System.out.println("Ho cancellato il file");
            } else {
                //System.out.println("Impossibile cancellare il file");
            }

        }

        //System.out.println("--------------------------------------------------------------");
    }

    public static void creaDir(String Dir) {


        boolean success = (new File(Dir)).mkdirs();

        if (success) {
            //System.out.println("Ho creato: " + Dir);
        } else {
            //System.out.println("Impossibile creare: " + Dir);
        }

    }

    public static String getCreaDir(String Dir) {

        boolean success = (new File(Dir)).mkdirs();

        if (success) {
            //System.out.println("Ho creato: " + Dir);
            return Dir;
        } else {
            //System.out.println("Impossibile creare: " + Dir);
            return null;
        }

    }

    public static String StampaStackError(
            Exception e) {

        String s = "";
        StackTraceElement[] ste = e.getStackTrace();
        for (int w = 0; w < ste.length; w++) {
            s += "\t" + ste[w].toString() + "\n";
        }

        e.printStackTrace();
        return s;
    }

    public static String StampaStackErrorForHTML(
            Exception e) {

        String s = "";
        s +=
                "<br>----------- ERRORI ----------------<br>";
        s +=
                "<br>";
        StackTraceElement[] ste = e.getStackTrace();
        for (int w = 0; w
                < ste.length; w++) {
            s += ste[w].toString() + "<br>";
        }

        e.printStackTrace();
        return s;
    }

    public static String getCodiceCliente() {

        String cod = "";

        Random n = new Random();

        for (int i = 0; i < 6; i++) {
            cod += (char) getCharRandom(n.nextInt(45));
        }

        return cod.toUpperCase();
    }

    public static String getCodiceImg() {

        String cod = "";

        Random n = new Random();

        for (int i = 0; i
                < 6; i++) {
            cod += (char) getCharRandom(n.nextInt(45));
        }

        return cod.toUpperCase();
    }

    public static String getPassword() {

        String cod = "";

        Random n = new Random();

        for (int i = 0; i
                < 5; i++) {
            cod += (char) n.nextInt(9);
        }

        return cod.toUpperCase();
    }

    private static char getCharRandom(int i) {
        switch (i) {
            case 0:
                return 'A';
            case 1:
                return 'a';
            case 2:
                return 'e';
            case 3:
                return 'C';
            case 4:
                return 'c';
            case 5:
                return 'r';
            case 6:
                return 'F';
            case 7:
                return 'A';
            case 8:
                return 'E';
            case 9:
                return 'Q';
            case 10:
                return 'd';
            case 11:
                return 'n';
            case 12:
                return 'K';
            case 13:
                return 'z';
            case 14:
                return 'Y';
            case 15:
                return 'k';
            case 16:
                return 'H';
            case 17:
                return 'D';
            case 18:
                return 'T';
            case 19:
                return 'h';
            case 20:
                return 'g';
            case 21:
                return 'p';
            case 22:
                return 'R';
            case 23:
                return 'b';
            case 24:
                return 'l';
            case 25:
                return 'y';
            case 26:
                return '4';
            case 27:
                return 'v';
            case 28:
                return 'm';
            case 29:
                return 'S';
            case 30:
                return 'w';
            case 31:
                return 'B';
            case 32:
                return '5';
            case 33:
                return '6';
            case 34:
                return 'J';
            case 35:
                return '2';
            case 36:
                return '3';
            case 37:
                return '7';
            case 38:
                return 'B';
            case 39:
                return '8';
            case 40:
                return '9';
            case 41:
                return '4';
            case 42:
                return 'G';
            case 43:
                return 'L';
            case 44:
                return 'P';
            case 45:
                return 'Z';
            default:
                return 'T';
        }
    }

    public static String fromStringToHTMLCode(String a) {
        String ret = "";
        if (a != null) {
            for (int i = 0; i < a.length(); ++i) {
                char c = a.charAt(i);
                int j = (int) c;
                ret += "&#" + j + ";";
            }
        }
        return ret;
    }
    /*
     * public static LinkedList<Prodotto> MixRandomList(LinkedList<Prodotto> lo)
     * { LinkedList<Prodotto> res = new LinkedList<Prodotto>();
     *
     * Random r = new Random();
     *
     * while (!lo.isEmpty()) { int nextPos = 0; if (lo.size() > 1) { nextPos =
     * r.nextInt(lo.size()); } res.addFirst(lo.get(nextPos));
     * lo.remove(nextPos); } return res; }
     */
}
